package com.shouyun.modules.oss.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.shouyun.common.utils.DataUtils;
import com.shouyun.common.utils.DateUtils;
import com.shouyun.common.utils.Result;
import com.shouyun.modules.oss.service.OssService;
import com.shouyun.modules.security.user.SecurityUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.util.*;

/**
 * 文件上传
 *
 * @author Sunshouguo sunshouguo_java@163.com
 */
@RestController
@RequestMapping("oss/share")
public class OssShareController {
    @Autowired
    private OssService ossService;

    /**
     * 分享列表
     * @param params
     * @return
     */
    @GetMapping("list")
    public Result page(@RequestParam Map<String, String> params) {
        String userName = params.get("userName");
        String fileName = params.get("fileName");
        //返回信息
        List<JSONObject> shareList = new ArrayList<>();
        JSONObject shareAll = DataUtils.getData(DataUtils.SHARE);
        for (String sign : shareAll.keySet()) {
            JSONObject shareInfo = shareAll.getJSONObject(sign);
            String shareUserName = shareInfo.getString("userName");
            String shareFileName = shareInfo.getString("fileName");
            /*if((StringUtils.isBlank(userName) && StringUtils.isBlank(fileName))
                || (StringUtils.isNotBlank(userName) && StringUtils.isNotBlank(shareUserName) && shareUserName.contains(userName))
                || (StringUtils.isNotBlank(fileName) && StringUtils.isNotBlank(shareFileName) && shareFileName.contains(fileName))){
                shareList.add(shareAll.getJSONObject(sign));
            }*/
            boolean isAdd = (StringUtils.isBlank(userName) && StringUtils.isBlank(fileName));
            if (StringUtils.isNotBlank(userName) && StringUtils.isNotBlank(shareUserName)) {
                isAdd = shareUserName.contains(userName);
            }
            if (StringUtils.isNotBlank(fileName) && StringUtils.isNotBlank(shareFileName)) {
                isAdd = shareFileName.contains(fileName);
            }
            if (isAdd) {
                shareList.add(shareAll.getJSONObject(sign));
            }
        }
        return new Result().ok(orderByDate(shareList));
    }

    /**
     * 按日期排序
     *
     * @param shareList
     */
    public static List<JSONObject> orderByDate(List<JSONObject> shareList) {
        Collections.sort(shareList, new Comparator<JSONObject>() {
            @Override
            public int compare(JSONObject d1, JSONObject d2) {
                long diff = d1.getDate("createDate").getTime() - d2.getDate("createDate").getTime();
                if (diff > 0)
                    return -1;
                else
                    return 1;
            }
        });
        return shareList;
    }

    /**
     * 创建分享
     * @param params
     * @return
     */
    @PostMapping("create")
    public Result create(@RequestBody Map<String, String> params) {
        String password = params.get("password");
        String path = params.get("path");
        if (StringUtils.isBlank(path) || StringUtils.isBlank(password) || StringUtils.isBlank(params.get("expireDay"))) {
            return new Result().error("缺少参数");
        }
        Integer expireDay = Integer.parseInt(params.get("expireDay"));
        //路径
        String workspace = ossService.getWorkspaceAndPath(path);
        File file = new File(workspace);
        String sign = getSign(workspace);
        JSONObject shareFile = DataUtils.getData(DataUtils.SHARE, sign);
        Date nowDate = new Date();
        if (shareFile != null && shareFile.size() > 0) {
            Integer shareExpireDay = shareFile.getInteger("expireDay");
            Date expireDate = shareFile.getDate("expireDate");
            if (shareExpireDay!=-1 && expireDate.before(nowDate)) {
                shareFile = null;
            }
        }
        if (shareFile == null || shareFile.size() <= 0) {
            shareFile = new JSONObject();
            shareFile.put("userName", SecurityUser.getUsername());
            shareFile.put("sign", sign);
            shareFile.put("path", path);
            shareFile.put("fileName", file.getName());
            shareFile.put("size", file.length());
            shareFile.put("createDate", DateUtils.format(nowDate, DateUtils.DATE_TIME_PATTERN));
            int suffixIndex = file.getName().lastIndexOf(".");
            if (suffixIndex > 0) {
                shareFile.put("suffix", file.getName().substring(suffixIndex + 1));
            }
            shareFile.put("password", password);
            shareFile.put("expireDay", expireDay);
            shareFile.put("expireDate", expireDay != -1 ? DateUtils.addDateDays(nowDate, expireDay) : expireDay);
            DataUtils.setData(DataUtils.SHARE, sign, shareFile);
        }
        return new Result().ok(shareFile);
    }

    /**
     * 取消分享
     * @param sign
     * @return
     */
    @PostMapping("remove/{sign}")
    public Result remove(@PathVariable("sign") String sign) {
        if (StringUtils.isBlank(sign)) {
            return new Result().error("缺少参数");
        }
        JSONObject shareFile = DataUtils.getData(DataUtils.SHARE, sign);
        Date nowDate = new Date();
        if (shareFile != null && shareFile.size() > 0) {
            DataUtils.removeData(DataUtils.SHARE, sign);
        }
        return new Result();
    }

    private String getSign(String workspace) {
        Base64.Encoder encoder = Base64.getEncoder();
        String sign = encoder.encodeToString(workspace.getBytes());
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_";
        String result="";
        for (int i = 0; i < sign.length(); i++) {
            String item=String.valueOf(sign.charAt(i));
            if(chars.contains(item)){
                result+=item;
            }
        }
        return result;
    }

    /**
     * 查看分享
     * @param sign
     * @return
     */
    @GetMapping("getInfo/{sign}")
    public Result getInfo(@PathVariable("sign") String sign) {
        if (StringUtils.isBlank(sign)) {
            return new Result().error("缺少参数");
        }
        JSONObject shareFile = DataUtils.getData(DataUtils.SHARE, sign);
        Date nowDate = new Date();
        if (shareFile != null && shareFile.size() > 0) {
            Date expireDate = shareFile.getDate("expireDate");
            if (expireDate.after(nowDate)) {
                shareFile = null;
                DataUtils.removeData(DataUtils.SHARE, sign);
            }
        }
        return new Result().ok(shareFile);
    }

    /**
     * 查看分享
     * @param params
     * @return
     */
    @GetMapping("getInfoByPath")
    public Result getInfo(@RequestParam Map<String, String> params) {
        String path = params.get("path");
        if (StringUtils.isBlank(path)) {
            return new Result().error("缺少参数");
        }
        //路径
        String workspace = ossService.getWorkspaceAndPath(path);
        File file = new File(workspace);
        String sign = getSign(workspace);

        JSONObject shareFile = DataUtils.getData(DataUtils.SHARE, sign);
        Date nowDate = new Date();
        if (shareFile != null && shareFile.size() > 0) {
            Integer shareExpireDay = shareFile.getInteger("expireDay");
            Date expireDate = shareFile.getDate("expireDate");
            if (shareExpireDay!=-1 && expireDate.before(nowDate)) {
                shareFile = null;
                DataUtils.removeData(DataUtils.SHARE, sign);
            }
        }
        Map<String, Object> resultMap = Maps.newHashMapWithExpectedSize(5);
        resultMap.put("shareFile", shareFile);
        resultMap.put("exists", file.exists());
        if (file.exists()) {
            resultMap.put("fileName", file.getName());
            resultMap.put("size", file.length());
            int suffixIndex = file.getName().lastIndexOf(".");
            if (suffixIndex > 0) {
                resultMap.put("suffix", file.getName().substring(suffixIndex + 1));
            }
        }
        return new Result().ok(resultMap);
    }
}